package com.sunfeng.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author : 清风冷影
 * @Description:  多任务执行 只要有一个执行完毕就可以 再次执行
 * @Date : 2021/11/15  21:37
 */
public class ThreadTest3 {

    public static ExecutorService executorService = Executors.newFixedThreadPool(10);
    public static void main(String[] args)  {
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> "任务1", executorService);
        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> "任务2", executorService);
        CompletableFuture<String> future03 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "任务3";
        });

    // 只要异步线程队列有一个任务率先完成就返回，这个特性可以用来获取最快的那个线程结果。
        CompletableFuture<Object> anyOf = CompletableFuture.anyOf(future01, future02, future03);

    // 获取若干个任务中最快完成的任务结果
    // .join()和.get()都会阻塞并获取线程的执行情况
    // .join()会抛出未经检查的异常，不会强制开发者处理异常 .get()会抛出检查异常，需要开发者处理
        try {
            Object o1 = anyOf.get();
            System.out.println(o1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        Object o2 = anyOf.join();
        System.out.println(o2);
        executorService.shutdown();
    }
}
